<template>
  <el-upload
    class="avatar-uploader"
    action="#"
    :http-request="upload"
    :show-file-list="false"
    :on-success="handleAvatarSuccess"
    :before-upload="beforeAvatarUpload"
  >
    <img v-if="value" :src="value" class="avatar">
    <i v-else class="el-icon-plus avatar-uploader-icon" />
  </el-upload>
</template>

<style>
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
</style>

<script>

// 下面的代码是固定写法
const COS = require('cos-js-sdk-v5')
// 填写自己腾讯云cos中的key和id (密钥)
const cos = new COS({
  SecretId: 'AKIDjJeleIhsIWVIySkocEdy8E7lCH8mESYT', // 身份识别ID
  SecretKey: 'tc9UaR2h8Jn9KGwPegW8arzxmOp5ELLU' // 身份秘钥
})
export default {
  props: {
    value: {
      type: String,
      required: true
    }
  },
  data() {
    return {
      imageUrl: ''
    }
  },
  methods: {
    upload(params) {
      console.log(params.file)
      // 自定义上传行为
      cos.putObject({
        Bucket: 'lanxi-1314477367', /* 存储桶 */
        Region: 'ap-nanjing', /* 存储桶所在地域，必须字段 */
        Key: '1.jpg', /* 文件名 */
        StorageClass: 'STANDARD', // 上传模式, 标准模式
        Body: params.file, // 上传文件对象
        onProgress: (progressData) => {
          console.log(JSON.stringify(progressData))
        }
      }, (err, data) => {
        console.log(err || data)
        // 上传成功之后
        this.imageUrl = 'http://' + data.Location
        this.$emit('input', this.imageUrl)
      })
    },
    handleAvatarSuccess(res, file) {
      this.imageUrl = URL.createObjectURL(file.raw)
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isJPG && isLt2M
    }
  }
}
</script>
